package com.jams.goodox.activity.serve.meet;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseQuickAdapter.OnRecyclerViewItemClickListener;
import com.chad.library.adapter.base.BaseViewHolder;
import com.hangzhou.jin.customview.LoadView;
import com.hangzhou.jin.customview.SpaceItemDecoration;
import com.jams.goodox.BaseFragment;
import com.jams.goodox.R;
import com.jams.goodox.activity.ChoosePayActivity;
import com.jams.goodox.constant.Constant;
import com.jams.goodox.constant.Constants;
import com.jams.goodox.entity.MeetHistory;
import com.jams.goodox.entity.PageInfo;
import com.jams.goodox.entity.PayInfo;
import com.jams.goodox.entity.resp.MeetHistoryResp;
import com.jams.goodox.net.RetrofitCallbackListener;
import com.jams.goodox.net.services.ServiceService;
import com.jams.goodox.utils.DataCacheManager;
import com.jams.goodox.utils.DensityUtil;
import com.jams.goodox.utils.ToastUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import retrofit2.Call;

/**
 * 场地预定记录页
 * Created by jams_zhen on 2017/5/10.
 */

public class MeetHistoryFragment extends BaseFragment {

    @Bind(R.id.recycleView)
    RecyclerView recycleView;
    @Bind(R.id.loadView)
    LoadView loadView;
    @Bind(R.id.swipeRefresh)
    SwipeRefreshLayout swipeRefresh;

    private BaseQuickAdapter baseQuickAdapter;

    private List<MeetHistory> meetHistories;

    private boolean isCanUse;//是否可使用
    private int curPage = 1;

    public static MeetHistoryFragment getInstance(boolean canUse) {
        MeetHistoryFragment meetHistoryFragment = new MeetHistoryFragment();
        Bundle bundle = new Bundle();
        bundle.putBoolean("canUse", canUse);
        meetHistoryFragment.setArguments(bundle);
        return meetHistoryFragment;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.meet_history_fragment, container, false);
        ButterKnife.bind(this, view);

        isCanUse = getArguments().getBoolean("canUse");

        meetHistories = new ArrayList<>();
        recycleView.setLayoutManager(new LinearLayoutManager(mContext));
        baseQuickAdapter = new BaseQuickAdapter<MeetHistory>(R.layout.meet_history_item, meetHistories) {
            @Override
            protected void convert(BaseViewHolder baseViewHolder,final MeetHistory meetHistory) {
                baseViewHolder.setText(R.id.tx_time, meetHistory.getMeetContinueTime());
                baseViewHolder.setText(R.id.tx_en_time, meetHistory.getEnTime());
                baseViewHolder.setText(R.id.tx_room, String.format("#%s#", meetHistory.getMeetRoom()));
                baseViewHolder.setText(R.id.tx_place, meetHistory.getMeetPlace());
                TextView txEnTime=baseViewHolder.getView(R.id.tx_en_time);
                txEnTime.setTextColor(("进行中".equalsIgnoreCase(meetHistory.getEnTime())) ?Color.parseColor("#333333"):Color.parseColor("#aaaaaa"));
                baseViewHolder.setVisible(R.id.relative_pay, meetHistory.isNeedPay());
                baseViewHolder.setVisible(R.id.tx_allMoney, false);
                baseViewHolder.setVisible(R.id.tx_hj,false);
                baseViewHolder.setText(R.id.tx_empty_time,  meetHistory.getPayEmptyTime());
                baseViewHolder.setText(R.id.tx_order_num,meetHistory.getOrderNum());
                baseViewHolder.setOnClickListener(R.id.tx_pay, new View.OnClickListener() {//前往付款页面
                    @Override
                    public void onClick(View view) {
                        goPay(meetHistory);
                    }
                });
            }
        };
        recycleView.setAdapter(baseQuickAdapter);
        baseQuickAdapter.openLoadMore(PAGE_SIZE, true);

        // 自定义上拉View
        baseQuickAdapter.setLoadingView(getLoadMoreBootView(mContext));

        baseQuickAdapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                loadData(true);
            }
        });
        recycleView.addItemDecoration(new SpaceItemDecoration(DensityUtil.dp2px(getContext(), 8)));
        loadView.loading();
        loadData(false);
        swipeRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                // 刷新代码
                curPage = 1;
                loadData(false);
            }
        });
        baseQuickAdapter.setOnRecyclerViewItemClickListener(new OnRecyclerViewItemClickListener() {
            @Override
            public void onItemClick(View view, int i) {
                Intent intent = new Intent(getContext(),MeetOrderDetailActivity.class);
                intent.putExtra("OrderId",meetHistories.get(i).getOrderId());
                intent.putExtra("payInfo",meetHistories.get(i).getPay());
                startActivityForResult(intent,Constants.REQUEST_SIMPLE);
            }
        });
        return view;
    }

    /**
     * 前往支付
     * @param meetHistory 列表item
     */
    private void goPay(MeetHistory meetHistory){
        PayInfo payInfo=meetHistory.getPay();//支付对象
        if(payInfo==null)return;
        Intent intent = new Intent(mContext, ChoosePayActivity.class);
        if (meetHistory.getRedPacket()!=0)
            payInfo.setRedPacketMoney(meetHistory.getRedPacket());
//        intent.putExtra("come", 1);//此处直接返回列表
        payInfo.setOrderCreateClassfiy(2);//此字段用来表示是企业服务下单
        payInfo.setPaySubCode(Constants.MEET_CODE);//该字段用于余额支付，
        payInfo.setThirdPayConfigType(Constants.PayType.Type_Meet);
        payInfo.setServerName("场地预订");
        payInfo.setOrderAllMoney( meetHistory.getTotalMoney());
        intent.putExtra("payInfo", payInfo);
        startActivity(intent);
    }

    private void loadData(boolean isLoadMore) {
        Map<String, String> params = Constant.getPagerParams(isLoadMore ? curPage + 1 : curPage);
        String enterpriseId = DataCacheManager.getInstance().getUser().getEnterpriseId();
        if (TextUtils.isEmpty(enterpriseId)) return;
        params.put("enterpriseId", enterpriseId);
        params.put("recordStatus", isCanUse ? "1" : "0");
        enqueue(createCallService(ServiceService.class).getMeetHistory(params), new RetrofitCallbackListener<MeetHistoryResp>() {
            @Override
            public void onSuccess(Call<MeetHistoryResp> call, MeetHistoryResp result) {
                loadView.loadComplete();
                swipeRefresh.setRefreshing(false);
                if (result.getData() == null || result.getData().getPageInfo() == null || result.getData().getResultList() == null) {
                    baseQuickAdapter.notifyDataChangedAfterLoadMore(false);
                    return;
                }
                PageInfo pageInfo = result.getData().getPageInfo();
                curPage = pageInfo.getCurPage();
                if(curPage==1)meetHistories.clear();
                meetHistories.addAll(result.getData().transform());
                baseQuickAdapter.notifyDataChangedAfterLoadMore(pageInfo.isHasMore());
                if(meetHistories.size()==0)loadView.loadCompleteNoData(R.mipmap.holder_no_history,"暂无记录");
            }

            @Override
            public void onError(String msg) {
                loadView.loadComplete();
                swipeRefresh.setRefreshing(false);
                baseQuickAdapter.notifyDataChangedAfterLoadMore(false);
                if(meetHistories.size()==0)loadView.loadCompleteNoData(R.mipmap.holder_no_history,"暂无记录");
                ToastUtil.show(msg);
            }
        });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode == Constants.REQUEST_SIMPLE){
            if(resultCode == Constants.RESULT_OK_SIMPLE){
                curPage=1;
                swipeRefresh.setRefreshing(true);
                loadData(false);
            }
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }
}
